package org.yzh.web.controller;

import io.github.yezhihao.netmc.session.Session;
import io.github.yezhihao.netmc.session.SessionManager;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.yzh.protocol.basics.JTMessage;
import org.yzh.protocol.codec.JTMessageDecoder;
import org.yzh.protocol.commons.JT1078;
import org.yzh.web.endpoint.MessageManager;

/**
 * @author Nick
 * @date 2025/9/16
 * @description Rtvs对接808平台
 */
@Slf4j
@RestController
@RequestMapping("/api/VideoControl")
@RequiredArgsConstructor
public class VideoController {

    private final MessageManager messageManager;
    private final SessionManager sessionManager;
    private final JTMessageDecoder decoder;

    @Operation(summary = "实时音视频传输状态通知及指令处理")
    @GetMapping
    public DeferredResult<String> videoControl(
            @RequestParam String Content,
            @RequestParam(required = false) Boolean IsSuperiorPlatformSend,
            @RequestParam(required = false) String CTags,
            @RequestParam(required = false) Integer ChSub,
            @RequestParam(required = false) Integer ChMain,
            @RequestParam(required = false) Integer ChBack,
            @RequestParam(required = false) Integer ChTalk,
            @RequestParam(required = false) Integer Sub,
            @RequestParam(required = false) Integer Main,
            @RequestParam(required = false) Integer Back,
            @RequestParam(required = false) Integer Talk) {

        // 打印log
        log.error("videoControl模块, Content: {}, IsSuperiorPlatformSend: {}, CTags: {}, ChSub: {}, ChMain: {}, ChBack: {}, ChTalk: {}, Sub: {}, Main: {}, Back: {}, Talk: {}",
                Content, IsSuperiorPlatformSend, CTags, ChSub, ChMain, ChBack, ChTalk, Sub, Main, Back, Talk);

        DeferredResult<String> result = new DeferredResult<>(10000L);

        try {
            // 解析16进制字符串为JTMessage
            ByteBuf byteBuf = Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(Content));
            JTMessage message = decoder.decode(byteBuf);

            if (message == null) {
                result.setResult("-1");
                return result;
            }

            // 获取消息ID
            int messageId = message.getMessageId();


            String clientId = message.getClientId();
            // 打印log
            log.error("videoControl模块, 消息ID: {}, 客户端ID: {}", messageId, clientId);
            // 检查设备是否在线
            Session session = sessionManager.get(clientId);
            if (session == null) {
                // 打印log
                log.error("videoControl模块, 设备ID: {} 不在线", clientId);
                result.setResult("0");
                return result;
            }


            // 根据不同的消息ID处理
            switch (messageId) {
                case JT1078.实时音视频传输状态通知: // 0x9105
                    // 直接通知设备，不需要等待应答
                    messageManager.notify(clientId, message).subscribe();
                    result.setResult("1");
                    break;

                case 0x9206: // 文件上传指令
                    // 发送消息并等待应答
                    messageManager.requestR(clientId, message, org.yzh.protocol.t808.T0001.class)
                            .subscribe(response -> {
                                if (response.getCode() == 200) {
                                    result.setResult(String.valueOf(response.getData().getSerialNo()));
                                } else if (response.getCode() == 4000) {
                                    result.setResult("0"); // 车辆不在线
                                } else {
                                    result.setResult("-1"); // 失败
                                }
                            });
                    break;

                case 0x9201: // 平台下发远程录像回放请求
                case 0x9205: // 查询资源列表
                    // 发送消息并等待应答
                    messageManager.requestR(clientId, message, org.yzh.protocol.t1078.T1205.class)
                            .subscribe(response -> {
                                if (response.getCode() == 200) {
                                    result.setResult(String.valueOf(response.getData().getMessageId()));
                                } else if (response.getCode() == 4000) {
                                    result.setResult("0"); // 车辆不在线
                                } else {
                                    result.setResult("-1"); // 失败
                                }
                            });
                    break;

                default:
                    // 其他指令，发送消息并等待应答
                    String finalClientId = clientId;
                    messageManager.requestR(clientId, message, org.yzh.protocol.t808.T0001.class)
                            .subscribe(response -> {

                                // 打印log
                                log.error("videoControl模块, 消息ID: {}, 客户端ID: {},请求报文:{}, 结果: {}", messageId, finalClientId, Content,response);
                                result.setResult("1");

//                                if (response.getCode() == 200) {
//                                    // 打印log
//                                    log.error("videoControl模块, 消息ID: {}, 客户端ID: {}, 应答ID: {}, 结果: {}", messageId, clientId, response.getData().getResponseMessageId(), response.getData().isSuccess());
//                                    result.setResult("1");
//                                } else if (response.getCode() == 4000) {
//                                    // 打印log
//                                    log.error("videoControl模块, 消息ID: {}, 客户端ID: {}, 应答ID: {}, 结果: {}", messageId, clientId, response.getData().getResponseMessageId(), response.getData().isSuccess());
//                                    result.setResult("0"); // 车辆不在线
//                                } else {
//                                    // 打印log
//                                    log.error("videoControl模块, 消息ID: {}, 客户端ID: {}, 应答ID: {}, 结果: {}", messageId, clientId, response.getData().getResponseMessageId(), response.getData().isSuccess());
//                                    result.setResult("-1"); // 失败
//                                }
                            });
                    break;
            }
        } catch (Exception e) {
            log.error("处理视频控制请求异常", e);
            result.setResult("-1");
        }

        return result;
    }


}
